package com.boot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.entity.Menu;
import com.boot.entity.User;
import com.boot.entity.dto.UpdatePasswordDto;
import com.boot.entity.dto.UserDto;
import com.boot.mapper.RoleMapper;
import com.boot.mapper.RoleMenuMapper;
import com.boot.mapper.UserMapper;
import com.boot.pojo.Result;
import com.boot.service.IMenuService;
import com.boot.service.UserService;
import com.boot.service.ex.NotFindUserException;
import com.boot.service.ex.NotOnlyOneException;
import com.boot.service.ex.UsernameExit;
import com.boot.service.ex.WithoutData;
import com.boot.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private IMenuService menuService;

    @Override
    public UserDto login(UserDto userDto) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",userDto.getUsername());
        queryWrapper.eq("password",userDto.getPassword());
        User user;
        try {
            user = getOne(queryWrapper);
        } catch (RuntimeException e) {
            throw new NotOnlyOneException("用户数据不只一条");
        }
        if(Objects.isNull(user)){
            throw new NotFindUserException("账号密码错误");
        }else{
            BeanUtil.copyProperties(user,userDto,true);
            String token = TokenUtils.getToken(user.getId().toString());
            userDto.setToken(token);
            String role = user.getRole();
            List<Menu> roleMenus = getRoleMenus(role);
            userDto.setMenus(roleMenus);
            return userDto;
        }
    }
    public Result register(User user){
        if(Objects.isNull(user)){
            throw new WithoutData("不能传入空值数据");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",user.getUsername());
        User user1 = userMapper.selectOne(queryWrapper);

        if(!Objects.isNull(user1)){
            throw new UsernameExit("用户名已经存在");
        }
        int insert = userMapper.insert(user);
        if(insert>0){
            return new Result().success("用户注册成功！");
        }
        return new Result().fail("用户注册失败");

    }

    @Override
    public Result updatePassword(UpdatePasswordDto updatePasswordDto) {
        if(Objects.isNull(updatePasswordDto)){
            throw new WithoutData("不能传入空值数据");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",updatePasswordDto.getUsername());
        queryWrapper.eq("password",updatePasswordDto.getOldPassword());
        User user = userMapper.selectOne(queryWrapper);
        if(Objects.isNull(user)){
            throw new NotFindUserException("没有找到对应的用户");
        }
        user.setPassword(updatePasswordDto.getNewPassword());
        int update = userMapper.update(user, queryWrapper);
        if(update>0){
            return new Result().success("密码修改完成");
        }
        return new Result().fail("密码修改错误");
    }


    @Override
    public Result updatePersonData(User user) {
        if(Objects.isNull(user)){
            throw new WithoutData("不能传入空值数据");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",user.getUsername());
        queryWrapper.eq("password",user.getPassword());
        User user1 = userMapper.selectOne(queryWrapper);
        if(Objects.isNull(user1)){
            throw new NotFindUserException("没有找到对应的用户");
        }

//        UserDto userDto = new UserDto(user1.getUsername(),user1.getPassword(),user1.getNickname(),user1.getAvatar());
        return new Result();
    }

    @Override
    public User getData(String username) {
        if("".equals(username)){
            throw new WithoutData("没有找到传递的数据");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        User user = userMapper.selectOne(queryWrapper);
        if(Objects.isNull(user)){
            throw new NotFindUserException("没有找到对应的数据");
        }
        return user;
    }

    //获取当前角色的菜单列表
    public List<Menu> getRoleMenus(String role){
        Integer roleId = roleMapper.selectByRole(role);
        List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId);
        List<Menu> menus = menuService.findMenus("");
        List<Menu> roleMenus = new ArrayList<>();
        menus.forEach(menu -> {
            if(menuIds.contains(menu.getId())){
                roleMenus.add(menu);
            }
            List<Menu> children = menu.getChildren();
            //removeIf 移除该角色中没有的子菜单
            children.removeIf(child -> !menuIds.contains(child.getId()));
        });
        return roleMenus;
    }
}
